package com.taomu.app.zongchouhuli.http.api;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import retrofit2.Converter;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.fastjson.FastJsonConverterFactory;


public class RetrofitBuilder {

    private String baseUrl;
    //okHttp请求拦截器
    private List<Interceptor> interceptors = new ArrayList<>(2);
    private Converter.Factory factory = FastJsonConverterFactory.create();

    public RetrofitBuilder(String baseUrl) {
        this.baseUrl = baseUrl;
    }

    public RetrofitBuilder setInterceptor(Interceptor interceptor) {
        interceptors.add(interceptor);
        return this;
    }

    /**
     * 设置数据转换方法，默认为FastJsonConverterFactory
     *
     * @param factory
     * @return
     */
    public RetrofitBuilder setFactory(Converter.Factory factory) {
        this.factory = factory;
        return this;
    }

    public Retrofit create() {
        Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(baseUrl)
            .addConverterFactory(FastJsonConverterFactory.create())
            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
            .client(getOkHttpClient(interceptors))
            .build();
        return retrofit;
    }

    private OkHttpClient getOkHttpClient(List<Interceptor> interceptors) {
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.connectTimeout(60, TimeUnit.SECONDS);
        if (!interceptors.isEmpty()) {
            for (Interceptor interceptor : interceptors) {
                if (interceptor != null) {
                    builder.addInterceptor(interceptor);
                }
            }
        }
        return builder.build();
    }
}


